import {
  Controller,
  Get,
  Post,
  Body,
  Patch,
  Param,
  Query,
  Delete,
  UseGuards,
  UploadedFiles,
  UseInterceptors,
  NotFoundException,
} from '@nestjs/common';
import { AnImgService } from './an-img.service';
import { CreateAnImgDto } from './dto/create-an-img.dto';
import { UpdateAnImgDto } from './dto/update-an-img.dto';
import { FindAnImgDto } from './dto/find-an-img.dto';
import { ApiTags, ApiOperation, ApiConsumes, ApiBody } from '@nestjs/swagger';
import { FilesInterceptor } from '@nestjs/platform-express';
import { UsersToken } from 'src/common/auth/decorators/users.decorator';

@ApiTags('图片')
@Controller('api/img')
export class AnImgController {
  constructor(private readonly anImgService: AnImgService) {}

  @Post('upload')
  @ApiOperation({ summary: '上传图片' })
  @ApiConsumes('multipart/form-data')
  @ApiBody({
    type: 'multipart/form-data',
    required: true,
    schema: {
      type: 'object',
      properties: {
        upload: {
          type: 'string',
          format: 'binary',
        },
      },
    },
  })
  @UseInterceptors(FilesInterceptor('files'))
  async create(
    @UploadedFiles() files,
    @Body() createAnImgDto: CreateAnImgDto,
    @UsersToken('userId') userId: string,
  ) {
    // 缩放尺寸
    createAnImgDto.scaleSize = createAnImgDto.scaleSize || 200;
    createAnImgDto.userId = userId;
    return this.anImgService.create(files, createAnImgDto);
  }

  @Get('list')
  findAll(@Query() query: FindAnImgDto) {
    return this.anImgService.findAll(query);
  }

  @Get(':id')
  findOne(@Param('id') id: string) {
    return this.anImgService.findOne(id);
  }

  @Post('update')
  update(@Body() updateAnImgDto: UpdateAnImgDto) {
    return this.anImgService.update(updateAnImgDto);
  }

  @Post('delete')
  remove(@Body('ids') ids: string) {
    if (!ids) {
      throw new NotFoundException(`参数错误`);
    }
    const aryIds = ids.split(',');
    return this.anImgService.remove(aryIds);
  }
}
